package com.joker.storehelper.client.android.http;

import android.support.annotation.NonNull;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.Credentials;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * OkHttp3 封装类
 * Created by wangziqiao on 2018/1/2.
 */

public class OkHttpUtil {
    private static CookieJar myCookieJar = new CookieJar() {
        Map<String, List<Cookie>> cookiesMap = new HashMap<>();

        @Override
        public void saveFromResponse(@NonNull HttpUrl url, @NonNull List<Cookie> cookies) {
            Log.i("joker", "OkHttpManager saveFromResponse " + url);
            cookiesMap.put(url.host(), cookies);
        }

        @Override
        public List<Cookie> loadForRequest(@NonNull HttpUrl url) {
            Log.i("joker", "OkHttpManager loadForRequest " + url);
            List<Cookie> cookies = cookiesMap.get(url.host());
            return cookies != null ? cookies : new ArrayList<Cookie>();
        }
    };

    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .cookieJar(myCookieJar).build();

    public static OkHttpClient getClient(){
        return okHttpClient;
    }

    public static JSONObject getJSON(String url) throws IOException {
        Request request =new Request.Builder().url(url).build();
        Response response = getClient().newCall(request).execute();
        String result = response.body().string();
        if(!Strings.isNullOrEmpty(result)){
            return JSON.parseObject(result);
        }
        return new JSONObject();
    }

    public static JSONObject postJSON(String url,Map<String,String> params) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        for(Map.Entry<String,String> entry:params.entrySet()){
            builder.add(entry.getKey(),entry.getValue());
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        Response response = getClient().newCall(request).execute();
        ResponseBody body = response.body();
        if(body != null && MediaType.parse("application/json;charset=UTF-8").equals(body.contentType())){
            String result = body.string();
            if(!Strings.isNullOrEmpty(result)){
                return JSON.parseObject(result);
            }
        }
        return new JSONObject();
    }

    public static JSONObject getJSONwithAuth(String url,String username,String password) throws IOException {
        String token = Credentials.basic(username,password);
        Request request =new Request.Builder().addHeader("Authorization",token).url(url).build();
        Response response = getClient().newCall(request).execute();
        String result = response.body().string();
        if(!Strings.isNullOrEmpty(result)){
            return JSON.parseObject(result);
        }
        return new JSONObject();
    }
}
